package vc.thinker.swagger

import com.yizisu.basemvvm.okHttpClient
import com.yizisu.basemvvm.utils.tryError
import org.apache.oltu.oauth2.client.OAuthClient
import org.apache.oltu.oauth2.client.request.OAuthClientRequest
import org.apache.oltu.oauth2.client.response.OAuthJSONAccessTokenResponse
import org.apache.oltu.oauth2.common.message.types.GrantType
import vc.thinker.swagger.auth.OAuthOkHttpClient

/**
 * 描述：Swagger工具类
 */
object SwaggerObj {
    //客户端认证id
    var APP_CLIENT_ID = ""
    //客户端认证秘钥
    var APP_CLIENT_SECRET = ""
    //登录后的token
    var APP_TOKEN = ""
        set(value) {
            field = value
            mOauth2ApiClient.setAccessToken(value)
        }
    //tokenUrl
    var TOKEN_URL = ""
    //url
    var BASE_URL = ""
    val mOauth2ApiClient by lazy { ApiClient("oauth2-password") }
    val mClientApiClient by lazy {
        ApiClient(
                "oauth2-clientcredentials",
                APP_CLIENT_ID,
                APP_CLIENT_SECRET
        )
    }


    fun <T> getApiWithToken(cls: Class<T>): T {
        mOauth2ApiClient.setAccessToken(APP_TOKEN)
        return mOauth2ApiClient.createService(cls)
    }

    fun <T> getApiNoToken(cls: Class<T>): T {
        return mClientApiClient.createService(cls)
    }

    /**
     * 用户登录
     */
    fun appUserLogin(
            phoneStr: String,
            pswStr: String,
            grantType: GrantType,
            result: (t: Throwable?, token: OAuthJSONAccessTokenResponse?) -> Unit
    ) {
        Thread {
            tryError(handlerError = {
                result.invoke(it, null)
            }) {
                val request = OAuthClientRequest
                        .tokenLocation(TOKEN_URL)
                        .setClientId(APP_CLIENT_ID)
                        .setClientSecret(APP_CLIENT_SECRET)
                        .setUsername(phoneStr)
                        .setPassword(pswStr)
                        .setGrantType(grantType)
                        .buildBodyMessage()
                val client = OAuthClient(OAuthOkHttpClient(okHttpClient))
                val accessTokenResponse = client.accessToken(request)
                APP_TOKEN = accessTokenResponse?.accessToken ?: ""
                result.invoke(null, accessTokenResponse)
                client.shutdown()
            }
        }.start()
    }
}